<template>
  <!-- 多条 折线图、柱形图、堆积图 -->
  <div>
    <div ref="fullScreenBox" :id="chartId" class="chart multiple"></div>
  </div>
</template>

<script>
import { mapState } from "vuex";
import Ecolors from "@/utils/chartColors";
import { resize, spaceTxt } from "@/utils/utils";
export default {
  mixins: [resize],
  props: {
    chartId: {
      type: String
    },
    needStack: {
      type: Boolean
    },
    chartData: {}
  },
  data() {
    return {
      chart: null,
      graphType: "line",
      colors: [],
      seriesData: [],
      currentLegendName: "" // 当前选中图例
    };
  },
  computed: {
    ...mapState(["curChartConfig"])
  },
  methods: {
    getCurChartConfig() {
      if (Object.keys(this.curChartConfig).length > 0) {
        let colors = [];
        this.curChartConfig.colors.forEach(v => {
          colors.push(v.color);
        });
        this.colors = [...colors, ...Ecolors.color];
        let graphType = this.curChartConfig.graphType;
        if (this.curChartConfig.graphType === "bar1") {
          graphType = "bar";
        } else if (this.curChartConfig.graphType === "bar2") {
          graphType = "bar";
        }
        this.graphType = graphType;
      }
      if (this.chartData && Object.keys(this.chartData).length > 0) {
        this.init();
      }
    },
    getSeriesData() {
      let seriesData = [];
      for (let i = 0; i < this.chartData.length; i++) {
        if (this.chartData[i][0] !== "product") {
          let obj = {
            stack: "group",
            type: this.graphType,
            name: this.chartData[i][0],
            seriesLayoutBy: "row",
            symbol: "circle",
            symbolSize: "8",
            connectNulls: true,
            smooth: true,
            scale: true,
            barMaxWidth: 26,
            label: {
              normal: {
                show: this.curChartConfig["showLabel"] || false,
                position: "right",
                color: "#6b6c7e",
                fontSize: this.curChartConfig["fontSize"] || 12,
                formatter: params => {
                  let value = params.data[params.encode.y[0]];
                  if (value === 0) {
                    // 如果为0，则不展示label
                    value = "";
                  }
                  return value;
                }
              }
            },
            itemStyle: {
              color: this.colors[i - 1]
            }
            // data: this.chartData[i]
          };
          if (this.needStack) {
            obj["stack"] = "all";
          }
          seriesData.push(obj);
        }
      }
      return seriesData;
    },
    init() {
      let seriesData = this.getSeriesData();
      // 图例
      let legend = {
        type: "scroll",
        show: this.curChartConfig["showLegend"],
        x: "center",
        y: "0",
        icon: "circle",
        textStyle: {
          color: "#6b6c7e"
        }
      };
      // 轴线
      let xAxisLine = {
        lineStyle: {
          color: this.curChartConfig["axisLine"].checked
            ? this.curChartConfig["axisLine"].color
            : "#f0f1f3",
          width: 2,
          type: this.curChartConfig["axisLine"].checked
            ? this.curChartConfig["axisLine"].type
            : "solid"
        }
      };
      // x轴分隔线
      let xSplitLine = {
        show: this.curChartConfig["xGridLine"].checked,
        lineStyle: {
          color: this.curChartConfig["xGridLine"].color || "#f0f1f3",
          type: this.curChartConfig["xGridLine"].type
        }
      };
      // y轴分隔线
      let ySplitLine = {
        show: this.curChartConfig["yGridLine"].checked,
        lineStyle: {
          color: this.curChartConfig["yGridLine"].color || "#f0f1f3",
          type: this.curChartConfig["yGridLine"].type
        }
      };
      // 背景色
      let backgroundColor = this.curChartConfig["showBgColor"].checked
        ? this.curChartConfig["showBgColor"].color
        : "#fff";
      let option = {
        tooltip: {
          confine: true,
          show: true,
          trigger: "axis",
          backgroundColor: "#fff",
          extraCssText: "box-shadow: 0 0 3px rgba(0, 0, 0, 0.3);",
          borderRadius: 0,
          padding: 5,
          textStyle: {
            color: "#000"
          }
        },
        // 图例
        legend,
        // 背景色
        backgroundColor,
        dataset: {
          source: JSON.parse(JSON.stringify(this.chartData))
        },
        xAxis: {
          type: "category",
          boundaryGap: true,
          // 轴线
          // axisLine: xAxisLine,
          axisLabel: {
            rotate: 40,
            interval: 0,
            margin: 10,
            textStyle: {
              color: "#666666"
            },

            formatter: function(value) {
              // return spaceTxt(label, 10);
              value = value.toString();
              if (value) {
                return value.split("-")[0];
              } else {
                return value;
              }
            }
          },
          // 分隔线
          splitLine: xSplitLine
        },
        yAxis: {
          type: "value",
          minInterval: 1,
          axisTick: {
            show: false
          },
          axisLine: {
            show: false,
            lineStyle: {
              color: "#f0f1f3",
              width: 2
            }
          },
          axisLabel: {
            textStyle: {
              color: "#666666"
            },
          },
          // 分隔线
          splitLine: ySplitLine
        },
        series: seriesData
      };

      option.tooltip.trigger = "axis";
      (option.color = this.colors),
        (option.grid = {
          top: "50px",
          right: "20px",
          left: "20px",
          bottom: "40px",
          containLabel: true
        });

      this.chart.clear();
      this.chart.setOption(option, true);

      // 图例反选
      this.chart.off("legendselectchanged");
      this.chart.on("legendselectchanged", obj => {
        const { selected, name } = obj;
        if (this.currentLegendName !== name) {
          Object.keys(selected).forEach(key => {
            selected[key] = key === name ? true : false;
          });
          this.currentLegendName = name;
        } else {
          if (selected[name] === false) {
            Object.keys(selected).forEach(key => {
              selected[key] = true;
            });
            this.currentLegendName = "";
          }
        }
        option.legend.selected = selected;
        this.chart.setOption(option);
      });

      // 后台报告下载
      this.chart.on("finished", () => {
        let tempId = this.$route.query.tempId;
        if (tempId) {
          this.getEchartImg(this.chart.getDataURL());
        }
      });

      this.$emit("chartDom", this.chart);
    },
    getEchartImg(base) {
      window.echartImg = base;

      let dom = document.getElementById("echartImgFinished");
      if (dom) {
        document.getElementById("app").removeChild(dom);
      }
      let _echartImg = document.createElement("div");
      _echartImg.setAttribute("id", "echartImgFinished");
      document.getElementById("app").appendChild(_echartImg);
    }
  },
  watch: {
    curChartConfig: {
      deep: true,
      handler: function() {
        this.getCurChartConfig();
      }
    },
    chartData() {
      if (Object.keys(this.chartData).length <= 0) {
        if (this.chart) this.chart.clear();
      } else {
        this.getCurChartConfig();
      }
    }
  },
  mounted() {
    this.chart = this.$echarts.init(document.getElementById(this.chartId));
    this.$emit("domRef", document.getElementById(this.chartId))
    this.getCurChartConfig();
  },
  destroyed() {
    this.chart.dispose();
    this.chart = null;
  }
};
</script>

<style lang="scss" scoped>

</style>
